package com.kyh.util.txt;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.kyh.util.DESUtil;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadTxtUtil {
	public static void main(String[] args) {
		
//		new ReadTxtUtil().readTxtByUrlAndAESDecode("http://file.cardezu.com/upload/upload/DBQ/02/ord/202004171830/ord_202004171830.txt", "YAmVxyQ#49s$N8bk");
		
		
		String str = new ReadTxtUtil().readTxtLineByUrlUnicode("https://files.cardezu.com/test/aa.txt");
		
		String[] aa = str.split("\n");
		for (int i = 3; i < aa.length; i++) {
			String a = aa[i];
			String[] bb = a.split("\t");
			for (int j = 0; j < bb.length; j++) {
				if (j == 0 || j == 20) {
					System.out.println(j + "---" + bb[j]);
				}
			}
			System.out.println("--------------------------");
		}
	}

	// 去读Excel的方法readExcel，该方法的入口参数为一个File对象
	@SuppressWarnings("unused")
	public static String readTxtByUrlAndAESDecode(String fileUrl, String key) {
    	String reStr = null;
		try {
			// 创建输入流，读取Excel
			URL url = new URL(fileUrl);
			InputStream inputStream = url.openStream();
            
    		ByteArrayOutputStream bos = null;
			bos = new ByteArrayOutputStream(inputStream.available());

			byte[] buffer = new byte[1024];
			int count = 0;
			while ((count = inputStream.read(buffer)) != -1) {
				bos.write(buffer, 0, count);
			}
			bos.flush();

			byte[] bytes = DESUtil.decodeAES(key.getBytes(), bos.toByteArray());
			reStr =  new String(bytes, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(reStr);
		return reStr;
	}

	/**
	 * 通过链接文件URL读取TXT文件
	 * @param fileUrl
	 * @return
	 */
	public static String readTxtByUrl(String fileUrl) {
    	String reStr = null;
    	BufferedReader br = null;
		try {
			// 创建输入流，读取Excel
			URL url = new URL(fileUrl);
			
			InputStream inputStream = url.openStream();
			
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            
			br = new BufferedReader(inputStreamReader);

			StringBuffer sb = new StringBuffer();
            String text = null;
            while((text = br.readLine()) != null){
                sb.append(text);
            }

			reStr = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
	            try {
	                br.close();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
			}
        }
		return reStr;
	}

	/**
	 * 通过链接文件URL读取TXT文件
	 * @param fileUrl
	 * @return
	 */
	public static String readTxtLineByUrl(String fileUrl) {
    	String reStr = null;
    	BufferedReader br = null;
		try {
			// 创建输入流，读取Excel
			URL url = new URL(fileUrl);
			
			InputStream inputStream = url.openStream();
			
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            
			br = new BufferedReader(inputStreamReader);

			StringBuffer sb = new StringBuffer();
            String text = null;
            while((text = br.readLine()) != null){
                sb.append(text + "\n");
            }

			reStr = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
	            try {
	                br.close();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
			}
        }
		return reStr;
	}

	/**
	 * 通过链接文件URL读取TXT文件
	 * @param fileUrl
	 * @return
	 */
	public static String readTxtLineByUrlUnicode(String fileUrl) {
		String reStr = null;
		BufferedReader br = null;
		try {
			String code = "UTF-16";
			
			// 创建输入流，读取Excel
			URL url = new URL(fileUrl);

			InputStream inputStream = url.openStream();

			InputStreamReader isr = new InputStreamReader(inputStream, code);  
            br = new BufferedReader(isr);  
			StringBuffer sb = new StringBuffer();
            String line = "";  
            while (null != (line = br.readLine())) {  
            	sb.append(line + "\n");  
            }  
            br.close();

            reStr = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
	            try {
	                br.close();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
			}
        }
		System.out.println(reStr);
		return reStr;
	}

	/**
	 * 获取表格中的表单
	 * @param fileUrl 完整的URL地址，如：http://file.cardezu.com/upload/manage/2020/04/01/14351115.xls
	 * @param sheetIndex 表单序号，从0开始
	 * @return
	 */
	public static Sheet getSheetByUrl(String fileUrl, int sheetIndex) {
		try {
			// 创建输入流，读取Excel
			URL url = new URL(fileUrl);
			InputStream is = url.openStream();
			// jxl提供的Workbook类
			Workbook wb = Workbook.getWorkbook(is);
			// Excel的页签数量
			int sheet_size = wb.getNumberOfSheets();
			if (sheet_size == 0) {
				return null;
			} else {
				return wb.getSheet(sheetIndex);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 去读Excel的方法readExcel，该方法的入口参数为一个File对象
	public static List<Map<Integer, String>> readSheet(File file, int sheetIndex) {
		try {
			// 创建输入流，读取Excel
			InputStream is = new FileInputStream(file.getAbsolutePath());
			// jxl提供的Workbook类
			Workbook wb = Workbook.getWorkbook(is);

			List<Map<Integer, String>> outerList = new ArrayList<Map<Integer, String>>();
			
			// 每个页签创建一个Sheet对象
			Sheet sheet = wb.getSheet(sheetIndex);
			// sheet.getRows()返回该页的总行数
			for (int i = 0; i < sheet.getRows(); i++) {
				Map<Integer, String> rowMap = new HashMap<Integer, String>();
				// sheet.getColumns()返回该页的总列数
				for (int j = 0; j < sheet.getColumns(); j++) {
					String cellinfo = sheet.getCell(j, i).getContents();
					if (cellinfo.isEmpty()) {
						continue;
					}
					
					rowMap.put(j, cellinfo);
				}
				outerList.add(rowMap);
			}
			return outerList;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 
	 * @param fieldNameArr	字段名数组
	 * @param sheet 表格的表单
	 * @param startRow 起始行，1代表第二行
	 * @return
	 */
	public static List<Map<String, Object>> sheetToJAFromSecondLine(String[] fieldNameArr, Sheet sheet, Integer startRow) {
		
		List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		
		// 总行数
		int rows = sheet.getRows();
		if (rows < 1) {
			return null;
		}
		
		// 遍历sheet
		for (int i = startRow; i < rows; i++) {
			// 获取Row并遍历
			Cell[] cells = sheet.getRow(i);
			
			Map<String, Object> map = new HashMap<String, Object>();
			for (int j = 0; j < cells.length; j++) {
				Cell cell = cells[j];
				String contents = cell.getContents();
				String fieldName = fieldNameArr[j];
				if (contents != null && contents.length() > 0) {
					map.put(fieldName, contents);
				}
				
			}
			listMap.add(map);
		}
		
		return listMap;
	}
}